package com.example.demo.service;

import com.example.demo.entity.Friends;
import com.example.demo.entity.JsonResult;
import com.example.demo.entity.Logs;
import com.example.demo.mapper.CustomerMapper;
import com.example.demo.util.qyf.ToolKit;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class PayServiceImpl implements PayService{

    @Autowired
    CustomerMapper customerMapper;

    static String merNo = "QYF201709161363";// 商户号
    static String key = "E3E8A34F48D0B837FCDDEEDB436510D6";// 签名MD5密钥,24位
    //    static String reqUrl = "http://wx.qyfpay.com:90/api/pay.action";
    static String reqUrl = "http://www.limapay.net/interface/chargebank.aspx";
    //    static String queryUrl="http://wx.qyfpay.com:90/api/queryPayResult.action";
    Logs logs = new Logs();

    //    @Override
//    public JsonResult pay(String phone) throws Exception {
//        JsonResult json = new JsonResult();
//        Map<String,String> map = new HashMap<>();
//        Map<String, String> metaSignMap = new TreeMap<String, String>();
//        String orderNum = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()); // 20位
//        orderNum += ToolKit.randomStr(3)+phone;
//        metaSignMap.put("orderNum", orderNum);
//        metaSignMap.put("version", "V3.0.0.0");
//        metaSignMap.put("charset", ToolKit.CHARSET);//
//        metaSignMap.put("random", ToolKit.randomStr(4));// 4位随机数
//        metaSignMap.put("merNo", merNo);
//        metaSignMap.put("netway", "WX");// WX:微信支付,ZFB:支付宝支付
//        metaSignMap.put("amount", "29800");// 单位:分
//        metaSignMap.put("goodsName", "认证会员");// 商品名称：20位
//        metaSignMap.put("callBackUrl", "http://1833g1872k.imwork.net/customer/getppUrl");// 回调地址
//        metaSignMap.put("callBackViewUrl", "http://1833g1872k.imwork.net/view");// 回显地址
//
//        String metaSignJsonStr = ToolKit.mapToJson(metaSignMap);
//        String sign = ToolKit.MD5(metaSignJsonStr + key, ToolKit.CHARSET);// 32位
//        metaSignMap.put("sign", sign);
//
//        byte[] dataStr = ToolKit.encryptByPublicKey(ToolKit.mapToJson(metaSignMap).getBytes(ToolKit.CHARSET),
//                ToolKit.PAY_PUBLIC_KEY);
//        String param = new BASE64Encoder().encode(dataStr);
//        String reqParam = "data=" + URLEncoder.encode(param, ToolKit.CHARSET) + "&merchNo=" + metaSignMap.get("merNo")
//                + "&version=" + metaSignMap.get("version");
//        String resultJsonStr = ToolKit.request(reqUrl, reqParam);
//        // 检查状态
//        JSONObject resultJsonObj = JSONObject.fromObject(resultJsonStr);
//        String stateCode = resultJsonObj.getString("stateCode");
//        if (!stateCode.equals("00")) {
//            map.put("stateCode",stateCode);
//            map.put("msg",resultJsonObj.getString("msg"));
//            json.setSuccess(false);
//            json.setData(map);
//            return json;
//        }
//        logs.setLogsCode(orderNum);
//        logs.setLogsTime( new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
//        logs.setPhone(phone);
//        logs.setLogsContent(metaSignMap.get("goodsName"));
//        Double d = Double.parseDouble(metaSignMap.get("amount"));
//        Integer m = d.intValue();
//        logs.setAmount(m);
//        logs.setLogsType("2");
//		customerMapper.saveLogs(logs);
////		String resultSign = resultJsonObj.getString("sign");
//        resultJsonObj.remove("sign");
////		String targetString = ToolKit.MD5(resultJsonObj.toString() + key, ToolKit.CHARSET);
////		if (targetString.equals(resultSign)) {
////		}
//        map.put("stateCode",stateCode);
//        map.put("code",resultJsonObj.getString("qrcodeUrl"));
//        map.put("msg",resultJsonObj.getString("msg"));
//        json.setData(map);
//        json.setSuccess(true);
//        return json;
//    }
    @Override
    public JsonResult pay(String phone) throws Exception {
//    public static void  main(String[] args) throws Exception {
        JsonResult json = new JsonResult();
        Map<String,String> map = new HashMap<>();
        Map<String, String> metaSignMap = new TreeMap<String, String>();
//        Integer rn = (int)Math.random()*900+100;
        String orderNum = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())+phone; // 20位
        metaSignMap.put("parter", "10046");//商户id
        metaSignMap.put("charset", ToolKit.CHARSET);//
        metaSignMap.put("orderid", orderNum);//商户系统自己的订单号
        metaSignMap.put("type", "ALIPAY");// 传入接口
        metaSignMap.put("value", "2");// 面值;单位:元
        metaSignMap.put("attach", "55555555555555555555555555");// 下行返回时原样返回
        metaSignMap.put("callBackUrl", "http://1833g1872k.imwork.net/customer/getppUrl");// 在返回过程中异步通知结果返回地址
        metaSignMap.put("hrefbackurl", "http://1833g1872k.imwork.net/view");// 浏览器同步返回地址
        String metaSignJsonStr = "parter="+metaSignMap.get("parter")+"&type="+metaSignMap.get("type")+
                "&orderid="+metaSignMap.get("orderid")+"&callbackurl="+metaSignMap.get("callBackUrl");
//        String sign = ToolKit.MD5(metaSignJsonStr + "B4414BFA7F1A39DBC9C6C31A8544583E", ToolKit.CHARSET);// 32位
        //md5加密
        String sign = MD5(metaSignJsonStr+"B4414BFA7F1A39DBC9C6C31A8544583E");
//        System.out.println(change(sign));
        metaSignMap.put("sign",sign);
        String key = "type="+metaSignMap.get("type")+"&parter="+metaSignMap.get("parter")+"&value="+metaSignMap.get("value")+"&orderid="
                +metaSignMap.get("orderid")+"&callbackurl="+metaSignMap.get("callBackUrl")+"&hrefbackurl="+metaSignMap.get("hrefbackurl")+
                "&sign="+metaSignMap.get("sign");
        String sendurl = reqUrl+"?"+key;
        map.put("code",sendurl);
        json.setData(map);
        json.setSuccess(true);
        return json;
    }
//
//    @Override
//    public String getppUrl(HttpServletRequest request, HttpServletResponse response) throws Throwable {
//        String data = request.getParameter("data");
//        byte[] result = ToolKit.decryptByPrivateKey(new BASE64Decoder().decodeBuffer(data), ToolKit.PRIVATE_KEY);
//        String resultData = new String(result, ToolKit.CHARSET);// 解密数据
//        JSONObject jsonObj = JSONObject.fromObject(resultData);
//        Map<String, String> metaSignMap = new TreeMap<String, String>();
//        metaSignMap.put("merNo", jsonObj.getString("merNo"));
//        metaSignMap.put("netway", jsonObj.getString("netway"));
//        metaSignMap.put("orderNum", jsonObj.getString("orderNum"));
//        metaSignMap.put("amount", jsonObj.getString("amount"));
//        metaSignMap.put("goodsName", jsonObj.getString("goodsName"));
//        metaSignMap.put("payResult", jsonObj.getString("payResult"));// 支付状态
//        metaSignMap.put("payDate", jsonObj.getString("payDate"));// yyyyMMddHHmmss
//        String jsonStr = ToolKit.mapToJson(metaSignMap);
//        String sign = ToolKit.MD5(jsonStr.toString() + key, ToolKit.CHARSET);
//        if (!sign.equals(jsonObj.getString("sign"))) {
//            return "1";
//        }
//        logs.setIsSure(1);
//        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        logs.setTimeSure(sd.format(new Date()));
//        logs.setLogsCode(jsonObj.getString("orderNum"));
//        logs.setFalseBack("支付成功！！！！");
//        customerMapper.updateLogs(logs);
//        //todo 如果付款成功 则改变会员
//        String b = jsonObj.getString("orderNum").substring(20);//获取用户手机号码，根据手机号码更改会员状态
//        customerMapper.updateMemberState(b);
//        //但会员认证成功以后，会给一级，二级，三级好友钱包中分别放入60,30,10元
//        //首先查询一二三级好友
//        Friends friends = customerMapper.getFriends(b);
//        //将奖励的好友的钱放入钱包
//        customerMapper.saveWalletMoney(6000,friends.getInviter1());
//        customerMapper.saveWalletMoney(3000,friends.getInviter2());
//        customerMapper.saveWalletMoney(1000,friends.getInviter3());
//        response.getOutputStream().write("0".getBytes());
//        return "0";
//    }

    public static String sendGet(String url) {
//        String result = "";
//        BufferedReader in = null;
//        try {
//            String urlNameString = url;
//            URL realUrl = new URL(urlNameString);
//            // 打开和URL之间的连接
//            URLConnection connection = realUrl.openConnection();
//            // 设置通用的请求属性
//            connection.setRequestProperty("accept", "*/*");
//            connection.setRequestProperty("connection", "Keep-Alive");
//            connection.setRequestProperty("user-agent",
//                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
//            connection.setRequestProperty("Accept-Charset", "gbk");
//            connection.setRequestProperty("contentType", "gbk");
//            // 建立实际的连接
//            connection.connect();
//            // 获取所有响应头字段
//            Map<String, List<String>> map = connection.getHeaderFields();
//            // 遍历所有的响应头字段
////            for (String key : map.keySet()) {
//////                System.out.println(key + "--->" + map.get(key));
////            }
//            // 定义 BufferedReader输入流来读取URL的响应
////            System.out.println(connection.getInputStream());
////            in = new BufferedReader(new InputStreamReader(
////                    connection.getInputStream(),"gbk"));
//            String line;
//            while ((line = in.readLine()) != null) {
//                result += line;
//            }
//        } catch (Exception e) {
//            System.out.println("发送GET请求出现异常！" + e);
//            e.printStackTrace();
//        }
//        // 使用finally块来关闭输入流
//        finally {
//            try {
//                if (in != null) {
//                    in.close();
//                }
//            } catch (Exception e2) {
//                e2.printStackTrace();
//            }
//        }
        return null;
    }

    public static    String change(String str){
        char[] ch = str.toCharArray();
        StringBuffer sbf = new StringBuffer();
        for(int i=0; i< ch.length; i++){
            sbf.append(charToLowerCase(ch[i]));
        }
        return sbf.toString();
    }
    /***转小写**/
    private static char charToLowerCase(char ch){
        if(ch <= 90 && ch >= 65){
            ch += 32;
        }
        return ch;
    }
    /**转大写**/
    private static char charToUpperCase(char ch){
        if(ch <= 122 && ch >= 97){
            ch -= 32;
        }
        return ch;
    }

    private static String MD5(String sourceStr) {
        String result = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(sourceStr.getBytes());
            byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            result = buf.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return result;
    }
}
